package com.hnas.eCard.web;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hnas.account.orm.Account;
import com.hnas.account.service.AccountService;
import com.hnas.api.dto.DTOResult;
import com.hnas.api.server.PostConnServer;
import com.hnas.api.util.CommonUtil;
import com.hnas.common.outdto.InitOrderForm;
import com.hnas.common.outdto.InitOrderReturnReceive;
import com.hnas.common.outdto.RechargePayForm;
import com.hnas.common.outdto.RechargePayReceive;
import com.hnas.common.util.CommonConstants;
import com.hnas.common.util.CommonReturn;
import com.hnas.common.util.CommonUtils;
import com.hnas.common.util.PostServerInfoGet;
import com.hnas.common.util.ResultCode;
import com.hnas.core.util.DateUtil;
import com.hnas.core.util.StringUtil;
import com.hnas.eCard.domain.CardMarkConstant;
import com.hnas.eCard.domain.ECardCommonFinalValue;
import com.hnas.eCard.domain.ECardStatus;
import com.hnas.eCard.domain.SendSMSThread;
import com.hnas.eCard.intf.CoreSaleCardOut;
import com.hnas.eCard.orm.AccECard;
import com.hnas.eCard.orm.CardTrail;
import com.hnas.eCard.orm.Commodit;
import com.hnas.eCard.orm.CommoditMrch;
import com.hnas.eCard.orm.CommoditOrderDetail;
import com.hnas.eCard.orm.EntityDenominationRe;
import com.hnas.eCard.orm.SaleCardOrderDetail;
import com.hnas.eCard.service.AccECardService;
import com.hnas.eCard.service.CardTrailService;
import com.hnas.eCard.service.CommoditMrchService;
import com.hnas.eCard.service.CommoditOrderDetailService;
import com.hnas.eCard.service.CommoditService;
import com.hnas.eCard.service.EntityCardOrderDetailService;
import com.hnas.eCard.service.SaleCardOrderDetailService;
import com.hnas.eCard.service.SaleCardOrderService;
import com.hnas.eCard.service.SaleCardRecordService;
import com.hnas.eCard.service.dto.DTOCommoditDetail;
import com.hnas.eCard.service.dto.DTOCommoditOrder;
import com.hnas.eCard.service.dto.DTOEntityCardOrder;
import com.hnas.eCard.service.dto.DTOEntityCardOrderDetail;
import com.hnas.eCard.service.dto.DTOSaleCardOrder;
import com.hnas.eCard.service.dto.DTOSaleCardOrderDetail;
import com.hnas.eCard.service.dto.search.DTOCommoditSearch;
import com.hnas.trade.domain.BuyCardRemindThread;
import com.hnas.trade.domain.FinalValueUtil;
import com.hnas.trade.domain.OrderStatus;
import com.hnas.trade.domain.OrderType;
import com.hnas.trade.domain.PayStatus;
import com.hnas.trade.domain.PaymentType;
import com.hnas.trade.domain.TradeType;
import com.hnas.trade.dto.DTOOrder;
import com.hnas.trade.dto.DTOTradeRecord;
import com.hnas.trade.orm.Order;
import com.hnas.trade.orm.TradeRecord;
import com.hnas.trade.service.OrderService;
import com.hnas.trade.service.TradeRecordService;
import com.hnas.trade.util.OrderNoUtil;

/**
 * 电子卡订单Controller
 * <p>Title:ECardOrderController </p>
 * <p>Description:</p>
 * <p>Componay:</p>
 * @author zhd.yu
 * @date 2018-02-26 14:05:31
 */
@Controller
@RequestMapping("/ecard/order")
public class ECardOrderController {

	private static Logger log = LoggerFactory.getLogger(ECardOrderController.class);
	private ObjectMapper objectMapper = new ObjectMapper();
	
	@Value("#{component.channel_qrcode_str}")
	private String channelQrcodeStr;
	@Value("#{component.SMS_BDT_SENDCARD}")
	private String SMS_BDT_SENDCARD;
	@Value("#{component.entity_mrch_ids}")
	private String entityMrchIds;
	@Value("#{component.commodit_mrch_id}")
	private String commoditMrchId;
	@Value("#{component.pic_suffix}")
	private String picUrlSuffix;
	
	@Autowired
	private SaleCardOrderService saleCardOrderService;
	@Autowired
	private PostServerInfoGet postServerInfoGet;
	@Autowired
	private SaleCardRecordService saleCardRecordService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private PostConnServer postConnServer;
	@Autowired
	private AccECardService accECardService;
	@Autowired
	private OrderService orderService;
	@Autowired
	private TradeRecordService tradeRecordService;
	@Autowired
	private SaleCardOrderDetailService saleCardOrderDetailService;
	@Autowired
	private CardTrailService cardTrailService;
	@Autowired
	private EntityCardOrderDetailService entityCardOrderDetailService;
	@Autowired
	private CommoditService commoditService;
	@Autowired
	private CommoditOrderDetailService commoditOrderDetailService;
	@Autowired
	private CommoditMrchService commoditMrchService;
	
	@Value("#{component['recharge_mrch_id']}")
	private String rechargeMrchId;
	@Value("#{component['merchant_id']}")
	private String merchantId;
	@Value("#{component['ecard_type']}")
	private String ecardType;
	
	private String tranCardNo = "1111111111111111111";
	
	
	@RequestMapping(value="/createSaleCardOrder",method=RequestMethod.POST)
	@ResponseBody
	/**
	 * 创建购卡订单
	 * @Title: createSaleCardOrder  
	 * @Description:  
	 * @param request
	 * @param response
	 * @return
	 * @throws
	 */
	public String createSaleCardOrder(HttpServletRequest request,HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, null);
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.acc_id));
			String saleCountStr = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.sale_count));
			String denominationStr = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.denomination));
			String frontUrl = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.front_url));
			String saleType = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.sale_type));
			String receivePhoneNo = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.receive_phone_no));
			String sendPhoneNo = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.send_phone_no));
			String receiveName = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.receive_name));
			String sendName = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.send_name));
			String sendMsg = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.send_msg));
			String openid = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.openid));
			String payChannel = CommonUtil.trimSpecial(jo.getString("pay_channel"));
			Long denomination = 0l;
			Integer saleCount = 0;
			Long amount = 0l;
			if(StringUtil.isEmpty(accId)) {//账户id为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, null);
			}
			if(StringUtil.isEmpty(saleCountStr)) {//售卡数量为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_182, null);
			}
			if(StringUtil.isEmpty(denominationStr)) {//卡面额为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_183, null);
			}
			denomination = Long.valueOf(denominationStr);
			saleCount = Integer.valueOf(saleCountStr);
			if(saleCount <= 0) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_221, null);
			}
			amount = denomination*saleCount;
//			amount = 1l;
			//判断购卡类型0-买给自己1-买给他人
			if(StringUtil.isEmpty(saleType)) {//购卡类型不能为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_222, null);
			}
			if(ECardCommonFinalValue.SALE_BY_MYSELF.equals(saleType)) {//买给自己
				
			}else if(ECardCommonFinalValue.SALE_FOR_OTHER.equals(saleType)) {//买给他人
				if(StringUtil.isEmpty(receivePhoneNo)) {//收卡人手机号不能为空
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_190, null);
				}
			}else {//不支持的购卡类型
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_223, null);
			}
			//查询主卡
			Account account = this.accountService.findById(accId);
			//1 创建购卡订单
			DTOSaleCardOrder orderDto = generateSaleCardOrder(accId, denomination, saleCount, amount,account.getUserName(),tranCardNo);
			DTOSaleCardOrderDetail generateSaleCardOrderDetail = generateSaleCardOrderDetail(denomination, saleCount, orderDto.getOrderNo(), receiveName, receivePhoneNo, saleType, sendName, sendPhoneNo, sendMsg, openid);
			Boolean result = this.saleCardOrderService.save(orderDto,generateSaleCardOrderDetail);
			if(!result) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_058, null);
			}
			//2 创建充值订单
			//根据用户id获取用户信息
			InitOrderForm form = new InitOrderForm();
			form.setBody(orderDto.getOrderDetail());
			form.setCardNo(tranCardNo);//TODO 需要指定一张卡，只做微信支付交易用，实际不往该卡中充值。因为没有主卡的概念了。
			form.setRechargeType("224102");
			form.setTotal(String.valueOf(amount/100.0));
			form.setPayChannel(payChannel);
			form.setCheckMaxBalance("0");//0表示不检查卡余额最大值
			form.setPayTypeId(ECardCommonFinalValue.PAYTYPE_SALE_CARD);
			//3 调用创建订单接口，如果创建失败，提示创建失败
			CommonReturn commonReturn1 = postServerInfoGet.initOrder(form);
			String resultCode1 = commonReturn1.getResultCode();
			if(!ResultCode.SUCCESS.equals(resultCode1)){
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_040, null);
			}
			InitOrderReturnReceive initOrderReturnReceive = (InitOrderReturnReceive) commonReturn1.getResultData();
			DTOOrder order = this.orderService.getByOrderNo(orderDto.getOrderNo());
			order.setSwiftNumber(initOrderReturnReceive.getSwiftNumber());
			order.setUpdateTime(DateUtil.dateTimeToString(new Date()));
			this.orderService.saveOrUpdate(order);
			//4 调用充值支付接口
			RechargePayForm form2 = new RechargePayForm();
			form2.setFrontUrl(frontUrl + order.getOrderNo());
			form2.setMerchantId(rechargeMrchId);
			form2.setSwiftNumber(order.getSwiftNumber());
			form2.setUserId(openid);
			CommonReturn commonReturn2 = postServerInfoGet.rechargePay(form2);
			String resultCode2 = commonReturn2.getResultCode();
			if(!ResultCode.SUCCESS.equals(resultCode2)){
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_041, null);
			}
			RechargePayReceive rechargePayReceive = (RechargePayReceive) commonReturn2.getResultData();
			//5 返回前端
			dtoResult.setResultCode(ResultCode.SUCCESS);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
			JSONObject data = new JSONObject();
			data.put("amount",rechargePayReceive.getAmount());
			data.put("prepay_id",rechargePayReceive.getPrepayId());
			data.put("swift_number",rechargePayReceive.getSwiftNumber());
			data.put("order_no",order.getOrderNo());
			data.put("pay_channel", initOrderReturnReceive.getPayChannel());
			dtoResult.setResultData(objectMapper.writeValueAsString(data));
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(data));
		}catch(Exception e) {
			e.printStackTrace();
			log.info("创建购卡订单异常："+e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}
	}
	
	@RequestMapping(value = "/WXPayCallback", method = RequestMethod.POST)
	@ResponseBody
	/**
	 * 购卡微信支付回调
	 * @Title: weChatPayCallback  
	 * @Description:  
	 * @param request
	 * @return
	 * @throws
	 */
	public String weChatPayCallback(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		try {
			String sendData = request.getParameter("sendData");
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String swiftNumber = jo.getString("swift_number");
			String payStatus = jo.getString("pay_status");
			String rechargeChannel = jo.getString("pay_channel");
			if (StringUtil.isEmpty(swiftNumber)) {
				log.info("微信支付回调处理："+ResultCode.ERROR_050+"-"+ResultCode.getResultValue(ResultCode.ERROR_050));
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_050, null);
			}
			if (StringUtil.isEmpty(payStatus)) {
				log.info("微信支付回调处理："+ResultCode.ERROR_049+"-"+ResultCode.getResultValue(ResultCode.ERROR_049));
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_049, null);
			}
			TradeRecord saleCardRecord = this.tradeRecordService.findBySwiftNumber(swiftNumber);
			if (saleCardRecord != null && StringUtil.isNotEmpty(saleCardRecord.getTradeSno())) {
				return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
			}
			//根据流水号获取订单记录，判断订单类型
			DTOOrder bySwiftNumber3 = this.orderService.getBySwiftNumber(swiftNumber);
			DTOOrder order = bySwiftNumber3;
			DTOOrder bySwiftNumber2 = order;
			DTOOrder bySwiftNumber = bySwiftNumber2;
			if(bySwiftNumber == null) {
				log.info("微信支付回调处理："+ResultCode.ERROR_051+"-"+ResultCode.getResultValue(ResultCode.ERROR_051));
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_051, null);
			}
			String orderType = bySwiftNumber.getOrderType();
			if(OrderType.DZKGK.getType().equals(orderType)) {
				//根据swiftNumber获取订单
				DTOSaleCardOrder orderDto = this.saleCardOrderService.getBySwiftNumber(swiftNumber);
				if (null == orderDto) {
					log.info("微信支付回调处理："+ResultCode.ERROR_051+"-"+ResultCode.getResultValue(ResultCode.ERROR_051));
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_051, null);
				}
				if(StringUtil.isNotEmpty(orderDto.getPayStatus())&&!PayStatus.Unpay.getStatus().equals(orderDto.getPayStatus())) {//如果已经是支付失败或者支付成功就不能处理了
					log.info("微信支付回调处理：订单已经处理了状态是-"+orderDto.getPayStatus());
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
				}
				orderDto.setPayStatus(payStatus);
				if (!OrderStatus.Payed.getStatus().equals(orderDto.getOrderStatus())) {
					orderDto.setPayEndTime(DateUtil.dateTimeToString(new Date()));
				}
				Order saleCardOrder = this.orderService.saveOrUpdate(orderDto);
				if (saleCardOrder == null) {
					log.info("微信支付回调处理："+ResultCode.ERROR_059+"-"+ResultCode.getResultValue(ResultCode.ERROR_059));
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_059, null);
				}
				if(PayStatus.Payed.getStatus().equals(payStatus)) {//支付成功
					//向核心发起发卡请求，如果成功就修改订单状态、存储交易记录，如果失败，就修改订单状态
					CoreSaleCardOut out = postConnServer.sellECards(orderDto.getOrderNo(), orderDto.getSaleCount(),orderDto.getDenomination(),merchantId,ecardType,swiftNumber,rechargeChannel);
					if(out == null) {//调用核心发卡接口异常
						log.info("微信支付回调处理："+ResultCode.ERROR_185+"-"+ResultCode.getResultValue(ResultCode.ERROR_185));
						return CommonUtils.createResult(dtoResult, ResultCode.ERROR_185, null);
					}
					String cardIds = out.getCardIds();
					if(orderDto.getSaleCount().equals(out.getCardNum()) && StringUtil.isNotEmpty(cardIds)) {//售卡成功
						//修改订单状态
						String tranEndTime = DateUtil.dateTimeToString(new Date());
						orderDto.setTradeEndTime(DateUtil.dateTimeToString(new Date()));
						orderDto.setOrderStatus(OrderStatus.Payed.getStatus());
						this.orderService.saveOrUpdate(orderDto);
						DTOSaleCardOrderDetail orderDetailDto = this.saleCardOrderDetailService.findDTOByOrderNo(orderDto.getOrderNo());
						orderDetailDto.setCards(cardIds);
						this.saleCardOrderDetailService.saveOrUpdate(orderDetailDto);
						String saleType = orderDetailDto.getSaleType();
						if(ECardCommonFinalValue.SALE_FOR_OTHER.equals(saleType)) {//买给自己
							String[] cardNos = cardIds.split(",");
							if(cardNos != null && cardNos.length > 0) {//如果是买给他人，需要存储赠送记录
								this.cardTrailService.batchSave(orderDto.getAccId(), orderDetailDto);
								JSONObject sendSMSReq = new JSONObject();
								List<String> paramList = new ArrayList<String>();
	//							String para1 = "您的朋友"+orderDetailDto.getSendPhoneNo()+"赠送给您"+orderDetailDto.getSaleCount()+"张“宝岛通电子卡”，请关注微信“宝岛通”公众服务号，登录微信虚拟卡平台，进行查收。如有疑问，请咨询客服";
	//							paramList.add(para1);
								paramList.add(orderDetailDto.getSendPhoneNo());
								paramList.add(orderDetailDto.getSaleCount().toString());
								paramList.add("963001");
								paramList.add(channelQrcodeStr);
								
								sendSMSReq.put(ECardCommonFinalValue.smsNum, orderDetailDto.getReceivePhoneNo());
								sendSMSReq.put(ECardCommonFinalValue.smsContentList, paramList);
								sendSMSReq.put(ECardCommonFinalValue.tempId, SMS_BDT_SENDCARD);
								SendSMSThread sendSMS = new SendSMSThread(sendSMSReq);
								Thread thread = new Thread(sendSMS);
								thread.start();
							}
						}else {//绑卡
							bindECard(orderDto.getAccId(), out.getRechargeAmt(), cardIds);
						}
						//存交易记录，发微信交易提醒
						saleCardOrder.setOrderStatus(OrderStatus.Payed.getStatus());
						DTOTradeRecord recordDto = transferSaleCardOrderToRecord(saleCardOrder);
						recordDto.setTradeEndTime(tranEndTime);
						TradeRecord tradeRecord = this.tradeRecordService.saveOrUpdate(recordDto);
						if (tradeRecord == null) {
							log.info("微信支付回调处理："+ResultCode.ERROR_039+"-"+ResultCode.getResultValue(ResultCode.ERROR_039));
							return CommonUtils.createResult(dtoResult, ResultCode.ERROR_039, null);// 存储交易记录失败
						}
						sendSaleCardWxMessage(orderDto);//发送购卡的微信消息
						return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
					}else {//支付成功，售卡失败
						orderDto.setOrderStatus(OrderStatus.PayFail.getStatus());
						this.orderService.saveOrUpdate(orderDto);
						log.info("微信支付回调处理："+ResultCode.ERROR_184+"-"+ResultCode.getResultValue(ResultCode.ERROR_184));
						return CommonUtils.createResult(dtoResult, ResultCode.ERROR_184, null);
					}
				}else if(PayStatus.PayFail.getStatus().equals(payStatus)) {//支付失败
					orderDto.setOrderStatus(OrderStatus.PayFail.getStatus());
					this.orderService.saveOrUpdate(orderDto);
					log.info("微信支付回调处理："+ResultCode.ERROR_184+"-"+ResultCode.getResultValue(ResultCode.ERROR_184));
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_184, null);
				}else{//未支付
					log.info("微信支付回调处理：未支付-"+orderDto.getOrderNo()+"-"+payStatus);
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
				}
			}else if(OrderType.STKGK.getType().equals(orderType)) {
				//根据swiftNumber获取订单
				DTOEntityCardOrder orderDto = this.saleCardOrderService.getEntityBySwiftNumber(swiftNumber);
				if (null == orderDto) {
					log.info("微信支付回调处理："+ResultCode.ERROR_051+"-"+ResultCode.getResultValue(ResultCode.ERROR_051));
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_051, null);
				}
				if(StringUtil.isNotEmpty(orderDto.getPayStatus())&&!PayStatus.Unpay.getStatus().equals(orderDto.getPayStatus())) {//如果已经是支付失败或者支付成功就不能处理了
					log.info("微信支付回调处理：订单已经处理了状态是-"+orderDto.getPayStatus());
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
				}
				orderDto.setPayStatus(payStatus);
				if (!OrderStatus.Payed.getStatus().equals(orderDto.getOrderStatus())) {
					orderDto.setPayEndTime(DateUtil.dateTimeToString(new Date()));
				}
				Order entityCardOrder = this.orderService.saveOrUpdate(orderDto);
				if (entityCardOrder == null) {
					log.info("微信支付回调处理："+ResultCode.ERROR_059+"-"+ResultCode.getResultValue(ResultCode.ERROR_059));
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_059, null);
				}
				if(PayStatus.Payed.getStatus().equals(payStatus)) {//支付成功
					String tranEndTime = DateUtil.dateTimeToString(new Date());
					orderDto.setTradeEndTime(DateUtil.dateTimeToString(new Date()));
					orderDto.setOrderStatus(OrderStatus.Payed.getStatus());
					this.orderService.saveOrUpdate(orderDto);
					DTOEntityCardOrderDetail orderDetailDto = this.entityCardOrderDetailService.findDTOByOrderNo(orderDto.getOrderNo());
					orderDetailDto.setEntityStatus(ECardCommonFinalValue.ENTITY_CARD_ORDER_UNUSE);
					this.entityCardOrderDetailService.saveOrUpdate(orderDetailDto);
					//存交易记录，发微信交易提醒
					entityCardOrder.setOrderStatus(OrderStatus.Payed.getStatus());
					DTOTradeRecord recordDto = transferSaleCardOrderToRecord(entityCardOrder);
					recordDto.setTradeEndTime(tranEndTime);
					TradeRecord tradeRecord = this.tradeRecordService.saveOrUpdate(recordDto);
					if (tradeRecord == null) {
						log.info("微信支付回调处理："+ResultCode.ERROR_039+"-"+ResultCode.getResultValue(ResultCode.ERROR_039));
						return CommonUtils.createResult(dtoResult, ResultCode.ERROR_039, null);// 存储交易记录失败
					}
					sendEntityCardWxMessage(orderDto);//发送购卡的微信消息
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
				}else if(PayStatus.PayFail.getStatus().equals(payStatus)) {//支付失败
					orderDto.setOrderStatus(OrderStatus.PayFail.getStatus());
					this.orderService.saveOrUpdate(orderDto);
					log.info("微信支付回调处理："+ResultCode.ERROR_184+"-"+ResultCode.getResultValue(ResultCode.ERROR_184));
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_184, null);
				}else{//未支付
					log.info("微信支付回调处理：未支付-"+orderDto.getOrderNo()+"-"+payStatus);
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
				}
			}else if(OrderType.GMSP.getType().equals(orderType)) {
				DTOOrder commoditOrderDto = this.orderService.getBySwiftNumber(swiftNumber);
				if (null == commoditOrderDto) {
					log.info("微信支付回调处理："+ResultCode.ERROR_051+"-"+ResultCode.getResultValue(ResultCode.ERROR_051));
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_051, null);
				}
				if(StringUtil.isNotEmpty(commoditOrderDto.getPayStatus())&&!PayStatus.Unpay.getStatus().equals(commoditOrderDto.getPayStatus())) {//如果已经是支付失败或者支付成功就不能处理了
					log.info("微信支付回调处理：订单已经处理了状态是-"+commoditOrderDto.getPayStatus());
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
				}
				commoditOrderDto.setPayStatus(payStatus);
				if (!OrderStatus.Payed.getStatus().equals(commoditOrderDto.getOrderStatus())) {
					commoditOrderDto.setPayEndTime(DateUtil.dateTimeToString(new Date()));
				}
				Order commoditOrder = this.orderService.saveOrUpdate(commoditOrderDto);
				if (commoditOrder == null) {
					log.info("微信支付回调处理："+ResultCode.ERROR_059+"-"+ResultCode.getResultValue(ResultCode.ERROR_059));
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_059, null);
				}
				if(PayStatus.Payed.getStatus().equals(payStatus)) {//支付成功
					String tranEndTime = DateUtil.dateTimeToString(new Date());
					commoditOrderDto.setTradeEndTime(DateUtil.dateTimeToString(new Date()));
					commoditOrderDto.setOrderStatus(OrderStatus.Payed.getStatus());
					this.orderService.saveOrUpdate(commoditOrderDto);
					
					CommoditOrderDetail commoditOrderDetail = this.commoditOrderDetailService.findByOrderNo(commoditOrderDto.getOrderNo());
					commoditOrderDetail.setState(ECardCommonFinalValue.COMMODIT_ORDER_UNUSE);
					this.commoditOrderDetailService.saveOrUpdate(commoditOrderDetail);
					//存交易记录，发微信交易提醒
					commoditOrderDto.setOrderStatus(OrderStatus.Payed.getStatus());
					DTOTradeRecord recordDto = transferCommoditOrderToRecord(commoditOrderDto);
					recordDto.setTradeEndTime(tranEndTime);
					TradeRecord tradeRecord = this.tradeRecordService.saveOrUpdate(recordDto);
					if (tradeRecord == null) {
						log.info("微信支付回调处理："+ResultCode.ERROR_039+"-"+ResultCode.getResultValue(ResultCode.ERROR_039));
						return CommonUtils.createResult(dtoResult, ResultCode.ERROR_039, null);// 存储交易记录失败
					}
					sendCommoditWxMessage(commoditOrderDto);//发送购卡的微信消息
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
				}else if(PayStatus.PayFail.getStatus().equals(payStatus)) {//支付失败
					commoditOrderDto.setOrderStatus(OrderStatus.PayFail.getStatus());
					this.orderService.saveOrUpdate(commoditOrderDto);
					log.info("微信支付回调处理："+ResultCode.ERROR_184+"-"+ResultCode.getResultValue(ResultCode.ERROR_184));
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_184, null);
				}else{//未支付
					log.info("微信支付回调处理：未支付-"+commoditOrderDto.getOrderNo()+"-"+payStatus);
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, null);
				}
			}
			log.info("订单类型有误（非16、17、18）！");
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}catch(Exception e) {
			e.printStackTrace();
			log.info("微信支付回调处理异常："+e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}
	}

	@RequestMapping("/getSaleCardOrderByOrderNo")
	@ResponseBody
	public String getSaleCardOrderByOrderNo(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		try {
			String sendData = request.getParameter("sendData");
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String orderNo = jo.getString("order_no");
			if (StringUtil.isEmpty(orderNo)) {//售卡订单号为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_048, null);
			}
			DTOSaleCardOrder saleCardOrder = this.saleCardOrderService.findByOrderNo(orderNo);
			SaleCardOrderDetail saleCardOrderDetail = this.saleCardOrderDetailService.findByOrderNo(orderNo);
			if (saleCardOrder == null) {//售卡订单不存在
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_047, null);
			}
			String saleType = saleCardOrderDetail.getSaleType();
			String receivePhoneNo = saleCardOrderDetail.getReceivePhoneNo();
			String sendPhoneNo = saleCardOrderDetail.getSendPhoneNo();
			String sendAccId = saleCardOrder.getAccId();
			//如果是买给别人，需要查询赠卡是否成功
			int status = 0;
			if(ECardCommonFinalValue.SALE_FOR_OTHER.equals(saleType)) {
				String cardIds = saleCardOrderDetail.getCards();
				if(StringUtil.isEmpty(cardIds)) {
					status = 0;
				}else {
					String[] cardNos = cardIds.split(",");
					if(cardNos != null && cardNos.length > 0) {
						//根据卡号查询赠卡记录
						List<CardTrail> cardTrails = this.cardTrailService.listByCards(sendAccId, sendPhoneNo, receivePhoneNo, StringUtil.getChangeString(cardIds));
						if(cardTrails != null && cardTrails.size() == saleCardOrderDetail.getSaleCount()) {//购卡时赠卡数量和购卡数量一致，就说明赠卡成功了，否则都算失败
							status = 0;
						}else {
							status = 1;//赠卡失败
						}
					}else {
						status = 2;//购卡失败
					}
				}
			}
			JSONObject orderRet = createOrderReturn(saleCardOrder,saleCardOrderDetail,status);
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(orderRet));
		}catch(Exception e) {
			e.printStackTrace();
			log.info("根据订单号查询订单信息异常："+e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}
	}
	
	/**
	 * 创建购实体卡订单
	 * @Title: createEntityCardOrder  
	 * @Description:  
	 * @param request
	 * @param response
	 * @return
	 * @throws
	 */
	@RequestMapping(value="/createEntityCardOrder",method=RequestMethod.POST)
	@ResponseBody
	public String createEntityCardOrder(HttpServletRequest request,HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, null);
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.acc_id));
//			String saleCountStr = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.sale_count));
//			String denominationStr = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.denomination));
			String frontUrl = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.front_url));
			String openid = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.openid));
			JSONArray denominationArr = jo.getJSONArray(ECardCommonFinalValue.denomination_arr);
			String payChannel = CommonUtil.trimSpecial(jo.getString("pay_channel"));
			Long denomination = 0l;
			Integer saleCount = 0;
			Long amount = 0l;
			if(StringUtil.isEmpty(accId)) {//账户id为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, null);
			}
			/*if(StringUtil.isEmpty(saleCountStr)) {//售卡数量为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_182, null);
			}
			if(StringUtil.isEmpty(denominationStr)) {//卡面额为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_183, null);
			}
			denomination = Long.valueOf(denominationStr);
			saleCount = Integer.valueOf(saleCountStr);
			if(saleCount <= 0) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_221, null);
			}
			amount = denomination*saleCount;
			*/
			amount = calculateAmount(denominationArr);
//			amount = calculateAmount1(denominationArr);
//			amount = 1l;
			//查询主卡
			Account account = this.accountService.findById(accId);
			//1 创建购卡订单
			DTOSaleCardOrder orderDto = generateEntityCardOrder(accId, denominationArr, amount,account.getUserName(),tranCardNo);
			DTOEntityCardOrderDetail generateEntityCardOrderDetail = generateEntityCardOrderDetail(orderDto.getOrderNo());
			List<EntityDenominationRe> entityDenominationReList = genernateEntityDenominationRe(denominationArr, orderDto.getOrderNo());
			boolean res = this.saleCardOrderService.saveEntityCard(orderDto,generateEntityCardOrderDetail,entityDenominationReList);
			if(!res) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_058, null);
			}
			//2 创建充值订单
			//根据用户id获取用户信息
			InitOrderForm form = new InitOrderForm();
			form.setBody(orderDto.getOrderDetail());
			form.setCardNo(tranCardNo);//TODO 需要指定一张卡，只做微信支付交易用，实际不往该卡中充值。因为没有主卡的概念了。
			form.setRechargeType("224102");
			form.setPayChannel(payChannel);
			form.setTotal(String.valueOf(amount/100.0));
			form.setCheckMaxBalance("0");//0表示不检查卡余额最大值
			form.setPayTypeId(ECardCommonFinalValue.PAYTYPE_ENTITY_CARD);
//			form.setPayTypeId(ECardCommonFinalValue.PAYTYPE_SALE_CARD);
			//3 调用创建订单接口，如果创建失败，提示创建失败
			CommonReturn commonReturn1 = postServerInfoGet.initOrder(form);
			String resultCode1 = commonReturn1.getResultCode();
			if(!ResultCode.SUCCESS.equals(resultCode1)){
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_040, null);
			}
			InitOrderReturnReceive initOrderReturnReceive = (InitOrderReturnReceive) commonReturn1.getResultData();
			DTOOrder order = this.orderService.getByOrderNo(orderDto.getOrderNo());
			order.setSwiftNumber(initOrderReturnReceive.getSwiftNumber());
			order.setUpdateTime(DateUtil.dateTimeToString(new Date()));
			this.orderService.saveOrUpdate(order);
			//4 调用充值支付接口
			RechargePayForm form2 = new RechargePayForm();
			form2.setFrontUrl(frontUrl + order.getOrderNo());
			form2.setMerchantId(rechargeMrchId);
			form2.setSwiftNumber(order.getSwiftNumber());
			form2.setUserId(openid);
			CommonReturn commonReturn2 = postServerInfoGet.rechargePay(form2);
			String resultCode2 = commonReturn2.getResultCode();
			if(!ResultCode.SUCCESS.equals(resultCode2)){
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_041, null);
			}
			RechargePayReceive rechargePayReceive = (RechargePayReceive) commonReturn2.getResultData();
			//5 返回前端
			dtoResult.setResultCode(ResultCode.SUCCESS);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
			JSONObject data = new JSONObject();
			data.put("amount",rechargePayReceive.getAmount());
			data.put("prepay_id",rechargePayReceive.getPrepayId());
			data.put("swift_number",rechargePayReceive.getSwiftNumber());
			data.put("order_no",order.getOrderNo());
			data.put("pay_channel", initOrderReturnReceive.getPayChannel());
			dtoResult.setResultData(objectMapper.writeValueAsString(data));
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(data));
		}catch(Exception e) {
			e.printStackTrace();
			log.info("创建购卡订单异常："+e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}
	}
	/**
	 * 根据账户id查询实体卡购卡订单
	 * @Title: getEntityListByAccId  
	 * @Description:  
	 * @param request
	 * @return
	 * @throws
	 */
	@RequestMapping("/getEntityListByAccId")
	@ResponseBody
	public String getEntityListByAccId(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		try {
			String sendData = request.getParameter("sendData");
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = jo.getString("acc_id");
			if (StringUtil.isEmpty(accId)) {//售卡订单号为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, null);
			}
			List<DTOEntityCardOrder> findEntityOrderListByAccId = this.saleCardOrderService.findEntityOrderListByAccId(accId);
			JSONObject orderRet = createEntityListReturn(findEntityOrderListByAccId);
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(orderRet));
		}catch(Exception e) {
			e.printStackTrace();
			log.info("根据订单号查询订单信息异常："+e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}
	}
	
	/**
	 * 根据账户id查询实体卡购卡订单
	 * @Title: getEntityListByAccId  
	 * @Description:  
	 * @param request
	 * @return
	 * @throws
	 */
	@RequestMapping("/getCommoditOrderListByAccId")
	@ResponseBody
	public String getCommoditOrderListByAccId(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		try {
			String sendData = request.getParameter("sendData");
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = CommonUtil.trimSpecial(jo.getString("acc_id"));
			String pageNoStr = CommonUtil.trimSpecial(jo.getString("page_no"));
			String pageSizeStr = CommonUtil.trimSpecial(jo.getString("page_size"));
			String stateStr = CommonUtil.trimSpecial(jo.getString("state"));
			if (StringUtil.isEmpty(accId)) {//售卡订单号为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, null);
			}
			int pageNo = Integer.valueOf(pageNoStr);
			int pageSize = Integer.valueOf(pageSizeStr);
			List<DTOCommoditOrder> commoditOrderList = this.commoditOrderDetailService.findOrderListByAccId(accId,pageNo,pageSize,stateStr);
			JSONObject orderRet = createCommoditOrderListReturn(commoditOrderList);
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(orderRet));
		}catch(Exception e) {
			e.printStackTrace();
			log.info("根据订单号查询订单信息异常："+e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}
	}
	
	/**
	 * 确认实体卡购卡消费
	 * @Title: confirmEntityCardConsume  
	 * @Description:  
	 * @param request
	 * @return
	 * @throws
	 */
	@RequestMapping("/confirmEntityCardConsume")
	@ResponseBody
	public String confirmEntityCardConsume(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		try {
			String sendData = request.getParameter("sendData");
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = CommonUtil.trimSpecial(jo.getString("acc_id"));
			String orderNo = CommonUtil.trimSpecial(jo.getString("order_no"));
			String mrchId = CommonUtil.trimSpecial(jo.getString("mrch_id"));
			String termSno = CommonUtil.trimSpecial(jo.getString("term_sno"));
			
			String customData = request.getParameter("customData");
			JSONObject customObj = JSON.parseObject(customData);
			String termNo = CommonUtil.trimSpecial(customObj.getString("termNo"));
			if (StringUtil.isEmpty(orderNo)) {//售卡订单号为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_048, null);
			}
			if (StringUtil.isEmpty(mrchId)) {//售卡订单号为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_089, null);
			}
			if (StringUtil.isEmpty(termNo)) {//售卡订单号为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_080, null);
			}
			DTOOrder orderDto = this.orderService.getByOrderNo(orderNo);
			String currentDateStr = DateUtil.dateTimeToString(new Date());
			if(OrderType.STKGK.getType().equals(orderDto.getOrderType())) {
				if(entityMrchIds.indexOf(mrchId) > -1) {
					boolean confirmConsume = this.entityCardOrderDetailService.confirmConsume(accId,orderNo,mrchId,termNo,currentDateStr);
					JSONObject result = new JSONObject();
					result.put("deal_time", currentDateStr);
					if(confirmConsume) {
						result.put(ECardCommonFinalValue.opt_status, "1");
					}else {
						result.put(ECardCommonFinalValue.opt_status, "0");
					}
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(result));
				}
			}else if(OrderType.GMSP.getType().equals(orderDto.getOrderType())) {
				//TODO 核销商品
				String findMrch = this.commoditMrchService.findMrch(orderDto.getOrderNo());
				if(findMrch!= null && findMrch.indexOf(mrchId) > -1) { 
					boolean confirmConsume = this.commoditOrderDetailService.confirmConsume(accId,orderNo,mrchId,termNo,termSno,currentDateStr);
					JSONObject result = new JSONObject();
					result.put("deal_time", currentDateStr);
					if(confirmConsume) {
						result.put(ECardCommonFinalValue.opt_status, "1");
					}else {
						result.put(ECardCommonFinalValue.opt_status, "0");
					}
					return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(result));
				}
			}
			return CommonUtils.createResult(dtoResult, ResultCode.ERROR_231, null);
		}catch(Exception e) {
			e.printStackTrace();
			log.info("根据订单号查询订单信息异常："+e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}
	}
	
	/**
	 * 根据账户id查询实体卡购卡订单
	 * @Title: getEntityListByAccId  
	 * @Description:  
	 * @param request
	 * @return
	 * @throws
	 */
	@RequestMapping("/getEntityOrderByOrderNo")
	@ResponseBody
	public String getEntityOrderByOrderNo(HttpServletRequest request) {
		DTOResult dtoResult = new DTOResult();
		JSONObject orderRet = new JSONObject();
		try {
			String sendData = request.getParameter("sendData");
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String orderNo = jo.getString("order_no");
			if (StringUtil.isEmpty(orderNo)) {//售卡订单号为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_048, null);
			}
			DTOOrder byOrderNo = this.orderService.getByOrderNo(orderNo);
			if(OrderType.STKGK.getType().equals(byOrderNo.getOrderType())) {
				DTOEntityCardOrder entityByOrderNo = this.saleCardOrderService.getEntityByOrderNo(orderNo);
				if(entityByOrderNo == null) {
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_047, null);
				}
				orderRet = createEntityReturn(entityByOrderNo);
				return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(orderRet));
			}else if(OrderType.GMSP.getType().equals(byOrderNo.getOrderType())) {
				DTOEntityCardOrder entityByOrderNo = this.saleCardOrderService.getCommoditByOrderNo(orderNo);
				if(entityByOrderNo == null) {
					return CommonUtils.createResult(dtoResult, ResultCode.ERROR_047, null);
				}
				orderRet = createEntityReturn(entityByOrderNo);
				return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(orderRet));
			}
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(orderRet));
		}catch(Exception e) {
			e.printStackTrace();
			log.info("根据订单号查询购实体卡订单信息异常："+e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}
	}
	
	/**
	 * 创建购买商品订单
	 * @return
	 */
	@RequestMapping("/createCommoditOrder")
	@ResponseBody
	public String createCommditOrder(HttpServletRequest request,HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, null);
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String accId = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.acc_id));
			String commoditArrStr = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.commodit_arr));
			String frontUrl = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.front_url));
			String openid = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.openid));
			String payChannel = CommonUtil.trimSpecial(jo.getString("pay_channel"));
			if(StringUtil.isEmpty(accId)) {//账户id为空
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_012, null);
			}
			//TODO 获取商品列表
			JSONArray commditArr = JSON.parseArray(commoditArrStr);
			Iterator<Object> iterator = commditArr.iterator();
			Long amount = 0l;
			List<DTOCommoditDetail> detailList = new ArrayList<DTOCommoditDetail>();
			while(iterator.hasNext()) {
				JSONObject temp = (JSONObject) iterator.next();
				String commoditId = temp.getString(ECardCommonFinalValue.commodit_id);
				String commoditNumStr = temp.getString(ECardCommonFinalValue.commodit_num);
				Commodit commodit = this.commoditService.findById(commoditId);
				Integer commoditNum = Integer.valueOf(commoditNumStr);
				DTOCommoditDetail comDet = new DTOCommoditDetail();
				BeanUtils.copyProperties(commodit, comDet);
				comDet.setCommoditNum(commoditNum);
				amount += comDet.getPrice()*commoditNum;
				detailList.add(comDet);
			}
			Collections.sort(detailList, new Comparator<DTOCommoditDetail>() {

				@Override
				public int compare(DTOCommoditDetail d1,DTOCommoditDetail d2) {
					if(d1.getPrice() - d2.getPrice() > 0) return 1;
					else if(d1.getPrice() - d2.getPrice() == 0) return 0;
					else return -1;
				}
			});
//			amount = 1l;
			//查询主卡
			Account account = this.accountService.findById(accId);
			if(account == null) {//账户不存在
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_011, null);
			}
			//1 创建购卡订单
			DTOOrder orderDto = generateCommoditOrder(accId, detailList, amount,account.getUserName(),tranCardNo);
			boolean res = this.orderService.createCommoditOrder(orderDto,detailList);
			if(!res) {
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_058, null);
			}
			//2 创建充值订单
			//根据用户id获取用户信息
			InitOrderForm form = new InitOrderForm();
			form.setBody(orderDto.getOrderDetail());
			form.setCardNo(tranCardNo);//TODO 需要指定一张卡，只做微信支付交易用，实际不往该卡中充值。因为没有主卡的概念了。
			form.setRechargeType("224102");
			form.setPayChannel(payChannel);
			form.setTotal(String.valueOf(amount/100.0));
			form.setCheckMaxBalance("0");//0表示不检查卡余额最大值
			form.setPayTypeId(ECardCommonFinalValue.PAYTYPE_COMMODIT);
			//3 调用创建订单接口，如果创建失败，提示创建失败
			CommonReturn commonReturn1 = postServerInfoGet.initOrder(form);
			String resultCode1 = commonReturn1.getResultCode();
			if(!ResultCode.SUCCESS.equals(resultCode1)){
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_040, null);
			}
			InitOrderReturnReceive initOrderReturnReceive = (InitOrderReturnReceive) commonReturn1.getResultData();
			DTOOrder order = this.orderService.getByOrderNo(orderDto.getOrderNo());
			order.setSwiftNumber(initOrderReturnReceive.getSwiftNumber());
			order.setUpdateTime(DateUtil.dateTimeToString(new Date()));
			this.orderService.saveOrUpdate(order);
			//4 调用充值支付接口
			RechargePayForm form2 = new RechargePayForm();
			form2.setFrontUrl(frontUrl + order.getOrderNo());
			form2.setMerchantId(commoditMrchId);
			form2.setSwiftNumber(order.getSwiftNumber());
			form2.setUserId(openid);
			CommonReturn commonReturn2 = postServerInfoGet.rechargePay(form2);
			String resultCode2 = commonReturn2.getResultCode();
			if(!ResultCode.SUCCESS.equals(resultCode2)){
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_041, null);
			}
			RechargePayReceive rechargePayReceive = (RechargePayReceive) commonReturn2.getResultData();
			//5 返回前端
			dtoResult.setResultCode(ResultCode.SUCCESS);
			dtoResult.setResultMsg(ResultCode.getResultValue(ResultCode.SUCCESS));
			JSONObject data = new JSONObject();
			data.put("amount",rechargePayReceive.getAmount());
			data.put("prepay_id",rechargePayReceive.getPrepayId());
			data.put("swift_number",rechargePayReceive.getSwiftNumber());
			data.put("order_no",order.getOrderNo());
			data.put("pay_channel", initOrderReturnReceive.getPayChannel());
			dtoResult.setResultData(objectMapper.writeValueAsString(data));
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(data));
		}catch(Exception e) {
			e.printStackTrace();
			log.info("创建购买商品订单异常："+e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}
	}
	
	/**
	 * 获取可购买商品的商家列表
	 * @return
	 */
	@RequestMapping("/getMrchList")
	@ResponseBody
	public String getMrchList(HttpServletRequest request,HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject jo = new JSONObject();
		try {
			List<CommoditMrch> commoditMrchList = this.commoditMrchService.listCommoditMrch();
			JSONArray ja = new JSONArray();
			if(commoditMrchList != null && commoditMrchList.size() > 0) {
				for(CommoditMrch m : commoditMrchList) {
					JSONObject temp = new JSONObject();
					temp.put(ECardCommonFinalValue.mrch_id, m.getMrchId());
					temp.put(ECardCommonFinalValue.mrch_name, m.getMrchName());
					temp.put(ECardCommonFinalValue.mrch_pic, picUrlSuffix+m.getMrchPic());
					ja.add(temp);
				}
			}
			jo.put("mrch_list", ja);
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(jo));
		}catch(Exception e) {
			e.printStackTrace();
			log.info("创建购买商品订单异常："+e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}
	}
	
	/**
	 * 根据商户编号获取商品列表
	 * @return
	 */
	@RequestMapping("/getCommoditListByMrch")
	@ResponseBody
	public String getCommoditListByMrch(HttpServletRequest request,HttpServletResponse response) {
		DTOResult dtoResult = new DTOResult();
		JSONObject ret = new JSONObject();
		try {
			String sendData = request.getParameter(ECardCommonFinalValue.SEND_DATA);
			if (StringUtil.isEmpty(sendData)) {
				// 请求参数有问题
				return CommonUtils.createResult(dtoResult, ResultCode.ERROR_10000, null);
			}
			JSONObject jo = (JSONObject) JSON.parse(sendData);
			String mrchId = CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.mrch_id));
			String pageNoStr =  CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.page_no));
			String pageSizeStr =  CommonUtil.trimSpecial(jo.getString(ECardCommonFinalValue.page_size));
			int pageNo = Integer.valueOf(pageNoStr);
			int pageSize = Integer.valueOf(pageSizeStr);
			DTOCommoditSearch criteria = new DTOCommoditSearch();
			criteria.setPageNo(pageNo);
			criteria.setPageSize(pageSize);
			criteria.setMrchId(mrchId);
			List<Commodit> list = this.commoditService.pageByMrchId(criteria);
			JSONArray ja = new JSONArray();
			if(list != null && list.size() > 0) {
				for(Commodit d : list) {
					JSONObject temp = new JSONObject();
					temp.put(ECardCommonFinalValue.commodit_id, d.getId());
					temp.put(ECardCommonFinalValue.commodit_name, d.getName());
					temp.put(ECardCommonFinalValue.commodit_price, d.getPrice());
					temp.put(ECardCommonFinalValue.commodit_old_price, d.getOldPrice());
					temp.put(ECardCommonFinalValue.commodit_desc, d.getDesc());
					temp.put(ECardCommonFinalValue.commodit_pic, picUrlSuffix+d.getPicUrl());
					ja.add(temp);
				}
			}
			ret.put("commodit_list", ja);
			return CommonUtils.createResult(dtoResult, ResultCode.SUCCESS, objectMapper.writeValueAsString(ret));
		}catch(Exception e) {
			e.printStackTrace();
			log.info("创建购买商品订单异常："+e.getMessage());
			return CommonUtils.createResult(dtoResult, ResultCode.FAIL, null);
		}
	}
	
	/**
	 * 根据购卡订单对象装配购卡交易记录对象
	 * @Title: transferSaleCardOrderToRecord  
	 * @Description:  
	 * @param saleCardOrder
	 * @return
	 * @throws
	 */
	private DTOTradeRecord transferSaleCardOrderToRecord(Order saleCardOrder) {
		DTOTradeRecord record = new DTOTradeRecord();
		BeanUtils.copyProperties(saleCardOrder, record);
		return record;
	}
	
	private DTOTradeRecord transferCommoditOrderToRecord(DTOOrder order) {
		DTOTradeRecord record = new DTOTradeRecord();
		BeanUtils.copyProperties(order, record);
		return record;
	}
	
	/**
	 * 生成售卡订单对象
	 * @Title: generateSaleCardOrder  
	 * @Description:  
	 * @param accId
	 * @param denomination
	 * @param saleCount
	 * @param amount
	 * @return
	 * @throws Exception
	 * @throws
	 */
	private DTOSaleCardOrder generateSaleCardOrder(String accId, Long denomination, Integer saleCount, Long amount,String userName,String cardNo) throws Exception{
		String orderType = OrderType.DZKGK.getType();
		DTOSaleCardOrder orderDto = new DTOSaleCardOrder();
		orderDto.setId(CommonUtils.getUUID());
		orderDto.setAccId(accId);
		orderDto.setAccName(userName);
		orderDto.setCardNo(cardNo);
//		orderDto.setCommidityId(null);
//		orderDto.setCommidityName(null);
		orderDto.setNeedPay(amount);
		orderDto.setRealPay(amount);
		orderDto.setOrderNo(OrderNoUtil.createOrderNo(accId, orderType));//TODO 生成订单号的工具方法
		orderDto.setOrderStatus(OrderStatus.Unpay.getStatus());
		orderDto.setPayStatus(PayStatus.Unpay.getStatus());
		orderDto.setOrderType(orderType);
		orderDto.setOrderParentType(OrderType.getOrderType(orderType).getParentType());
		orderDto.setOrderTypeName(OrderType.getOrderTypeName(orderType));
		orderDto.setPayment(PaymentType.WX.getType());
//		orderDto.setSubId(subId);//不填？
		orderDto.setTradeType(TradeType.WXH5.getType());//
		orderDto.setMrchId(rechargeMrchId);
		orderDto.setMrchName(FinalValueUtil.WeChatVirtualCard_MrchName);
//		orderDto.setTermNo(termNo);
		orderDto.setCreator(accId);
		orderDto.setUpdater(accId);
		orderDto.setCreateTime(DateUtil.dateTimeToString(new Date()));
		orderDto.setUpdateTime(DateUtil.dateTimeToString(new Date()));
		orderDto.setIsDeleted(false);
		
		orderDto.setSaleCount(saleCount);
		orderDto.setDenomination(denomination);
		return orderDto;
	}
	
	/**
	 * 生成售卡订单对象
	 * @Title: generateSaleCardOrder  
	 * @Description:  
	 * @param accId
	 * @param denomination
	 * @param saleCount
	 * @param amount
	 * @return
	 * @throws Exception
	 * @throws
	 */
	private DTOSaleCardOrder generateEntityCardOrder(String accId, JSONArray denominationArr,Long amount,String userName,String cardNo) throws Exception{
		String orderType = OrderType.STKGK.getType();
		DTOSaleCardOrder orderDto = new DTOSaleCardOrder();
		orderDto.setId(CommonUtils.getUUID());
		orderDto.setAccId(accId);
		orderDto.setAccName(userName);
		orderDto.setCardNo(cardNo);
//		orderDto.setCommidityId(null);
//		orderDto.setCommidityName(null);
		orderDto.setNeedPay(amount);
		orderDto.setRealPay(amount);
		orderDto.setOrderNo(OrderNoUtil.createOrderNo(accId, orderType));//TODO 生成订单号的工具方法
		orderDto.setOrderStatus(OrderStatus.Unpay.getStatus());
		orderDto.setPayStatus(PayStatus.Unpay.getStatus());
		orderDto.setOrderType(orderType);
		orderDto.setOrderParentType(OrderType.getOrderType(orderType).getParentType());
		orderDto.setOrderTypeName(OrderType.getOrderTypeName(orderType));
		orderDto.setPayment(PaymentType.WX.getType());
//		orderDto.setSubId(subId);//不填？
		orderDto.setTradeType(TradeType.WXH5.getType());//
		orderDto.setMrchId(rechargeMrchId);
		orderDto.setMrchName(FinalValueUtil.WeChatVirtualCard_MrchName);
//		orderDto.setTermNo(termNo);
		orderDto.setCreator(accId);
		orderDto.setUpdater(accId);
		orderDto.setCreateTime(DateUtil.dateTimeToString(new Date()));
		orderDto.setUpdateTime(DateUtil.dateTimeToString(new Date()));
		orderDto.setIsDeleted(false);
		orderDto.setOrderDetail(getOrderDetail(denominationArr));
		return orderDto;
	}
	
	
	/**
	 * 生成售卡订单对象
	 * @Title: generateSaleCardOrder  
	 * @Description:  
	 * @param accId
	 * @param denomination
	 * @param saleCount
	 * @param amount
	 * @return
	 * @throws Exception
	 * @throws
	 */
	private DTOOrder generateCommoditOrder(String accId, List<DTOCommoditDetail> detailList, Long amount,String userName,String cardNo) throws Exception{
		String orderType = OrderType.GMSP.getType();
		DTOOrder orderDto = new DTOSaleCardOrder();
		orderDto.setId(CommonUtils.getUUID());
		orderDto.setAccId(accId);
		orderDto.setAccName(userName);
		orderDto.setCardNo(cardNo);
//		orderDto.setCommidityId(null);
//		orderDto.setCommidityName(null);
		orderDto.setNeedPay(amount);
		orderDto.setRealPay(amount);
		orderDto.setOrderNo(OrderNoUtil.createOrderNo(accId, orderType));//TODO 生成订单号的工具方法
		orderDto.setOrderStatus(OrderStatus.Unpay.getStatus());
		orderDto.setPayStatus(PayStatus.Unpay.getStatus());
		orderDto.setOrderType(orderType);
		orderDto.setOrderParentType(OrderType.getOrderType(orderType).getParentType());
		orderDto.setOrderTypeName(OrderType.getOrderTypeName(orderType));
		orderDto.setPayment(PaymentType.WX.getType());
//		orderDto.setSubId(subId);//不填？
		orderDto.setTradeType(TradeType.WXH5.getType());//
		orderDto.setMrchId(rechargeMrchId);
		orderDto.setMrchName(FinalValueUtil.WeChatVirtualCard_MrchName);
//		orderDto.setTermNo(termNo);
		orderDto.setCreator(accId);
		orderDto.setUpdater(accId);
		orderDto.setCreateTime(DateUtil.dateTimeToString(new Date()));
		orderDto.setUpdateTime(DateUtil.dateTimeToString(new Date()));
		orderDto.setIsDeleted(false);
		orderDto.setOrderDetail(createCommoditDetail(detailList));
		return orderDto;
	}
	private String createCommoditDetail(List<DTOCommoditDetail> detailList) {
		JSONArray ja = new JSONArray();
		for(DTOCommoditDetail d : detailList) {
			JSONObject jo = new JSONObject();
			jo.put(ECardCommonFinalValue.commodit_id, d.getId());
			jo.put(ECardCommonFinalValue.commodit_num, d.getCommoditNum());
			jo.put(ECardCommonFinalValue.commodit_name, d.getName());
			jo.put(ECardCommonFinalValue.commodit_price, d.getPrice());
			ja.add(jo);
		}
		return ja.toJSONString();
	}

	/**
	 * 生成售卡订单详情对象
	 * @Title: generateSaleCardOrderDetail  
	 * @Description:  
	 * @param denomination
	 * @param saleCount
	 * @param orderNo
	 * @param receiveName
	 * @param receivePhoneNo
	 * @param saleType
	 * @param sendName
	 * @param sendPhoneNo
	 * @param sendMsg
	 * @return
	 * @throws
	 */
	private DTOSaleCardOrderDetail generateSaleCardOrderDetail(Long denomination,Integer saleCount,String orderNo,String receiveName,String receivePhoneNo,String saleType,String sendName,String sendPhoneNo,String sendMsg,String openid) {
		DTOSaleCardOrderDetail dto = new DTOSaleCardOrderDetail();
		dto.setCards(null);
		dto.setDenomination(denomination);
		dto.setId(CommonUtils.getUUID());
		dto.setOrderNo(orderNo);
		dto.setSaleCount(saleCount);
		dto.setReceiveName(receiveName);
		dto.setReceivePhoneNo(receivePhoneNo);
		dto.setSaleType(saleType);
		dto.setSendName(sendName);
		dto.setSendPhoneNo(sendPhoneNo);
		dto.setSendMsg(sendMsg);
		dto.setOpenid(openid);
		return dto;
	}
	
	/**
	 * 生成售实体卡订单详情对象
	 * @Title: generateSaleCardOrderDetail  
	 * @Description:  
	 * @param denomination
	 * @param saleCount
	 * @param orderNo
	 * @param receiveName
	 * @param receivePhoneNo
	 * @param saleType
	 * @param sendName
	 * @param sendPhoneNo
	 * @param sendMsg
	 * @return
	 * @throws
	 */
	private DTOEntityCardOrderDetail generateEntityCardOrderDetail(String orderNo) {
		DTOEntityCardOrderDetail dto = new DTOEntityCardOrderDetail();
		dto.setCards(null);
		dto.setId(CommonUtils.getUUID());
		dto.setOrderNo(orderNo);
		dto.setEntityStatus(ECardCommonFinalValue.ENTITY_CARD_ORDER_INIT);
		return dto;
	}
	
	private List<EntityDenominationRe> genernateEntityDenominationRe(JSONArray ja,String orderNo) {
		JSONObject[] arr = ja.toArray(new JSONObject[]{});
		List<EntityDenominationRe> list = new ArrayList<EntityDenominationRe>();
		for(int i = 0; i < arr.length; i++) {
			EntityDenominationRe temp = new EntityDenominationRe();
			JSONObject jo = arr[i];
			temp.setOrderNo(orderNo);
			temp.setCount(jo.getInteger("sale_count"));
			temp.setDenomination(jo.getLong("denomination"));
			temp.setId(CommonUtils.getUUID());
			list.add(temp);
		}
		return list;
	}
	
	private Long calculateAmount(JSONArray ja) {
		JSONObject[] arr = ja.toArray(new JSONObject[]{});
		Long amount = 0l;
		for(int i = 0; i < arr.length; i++) {
			JSONObject jo = arr[i];
			Integer count = jo.getInteger("sale_count");
			Long denomination = jo.getLong("denomination");
			amount += count*denomination;
		}
		return amount;
	}
	
	private Long calculateAmount1(JSONArray ja) {
		JSONObject[] arr = ja.toArray(new JSONObject[]{});
		Long amount = 0l;
		for(int i = 0; i < arr.length; i++) {
			JSONObject jo = arr[i];
			Integer count = jo.getInteger("sale_count");
			amount += count*1;
		}
		return amount;
	}
	
	/**
	 * 发送微信消息
	 * @Title: sendWxMessage  
	 * @Description:  
	 * @param orderDto
	 * @throws
	 */
	private void sendSaleCardWxMessage(DTOSaleCardOrder orderDto) {
		Account account = this.accountService.findById(orderDto.getAccId());
		JSONObject remindData = new JSONObject();
		remindData.put("openIdStr", account.getOpenId());
		remindData.put("modelType", "1");
		remindData.put("payValue", "￥" + orderDto.getRealPay() / 100.0);
		remindData.put("tranTime", orderDto.getTradeEndTime());
		remindData.put("tranSno", orderDto.getOrderNo());
		remindData.put("first", CommonConstants.FIRST_4);
		remindData.put("remark", CommonConstants.REMARK_1);
		BuyCardRemindThread remindTread = new BuyCardRemindThread(remindData);
		Thread thread = new Thread(remindTread);
		thread.start();
	}	
	
	/**
	 * 发送微信消息
	 * @Title: sendWxMessage  
	 * @Description:  
	 * @param orderDto
	 * @throws
	 */
	private void sendEntityCardWxMessage(DTOEntityCardOrder orderDto) {
		Account account = this.accountService.findById(orderDto.getAccId());
		JSONObject remindData = new JSONObject();
		remindData.put("openIdStr", account.getOpenId());
		remindData.put("modelType", "1");
		remindData.put("payValue", "￥" + orderDto.getRealPay() / 100.0);
		remindData.put("tranTime", orderDto.getTradeEndTime());
		remindData.put("tranSno", orderDto.getOrderNo());
		remindData.put("first", CommonConstants.FIRST_4);
		remindData.put("remark", CommonConstants.REMARK_1);
		BuyCardRemindThread remindTread = new BuyCardRemindThread(remindData);
		Thread thread = new Thread(remindTread);
		thread.start();
	}	
	
	private void sendCommoditWxMessage(DTOOrder orderDto) {
		Account account = this.accountService.findById(orderDto.getAccId());
		JSONObject remindData = new JSONObject();
		remindData.put("openIdStr", account.getOpenId());
		remindData.put("modelType", "1");
		remindData.put("payValue", "￥" + orderDto.getRealPay() / 100.0);
		remindData.put("tranTime", orderDto.getTradeEndTime());
		remindData.put("tranSno", orderDto.getOrderNo());
		remindData.put("first", CommonConstants.FIRST_6);
		remindData.put("remark", CommonConstants.REMARK_1);
		BuyCardRemindThread remindTread = new BuyCardRemindThread(remindData);
		Thread thread = new Thread(remindTread);
		thread.start();
	}
	/**
	 * 绑定电子卡
	 * @Title: bindECard  
	 * @Description:  
	 * @param orderDto
	 * @param out
	 * @param cardIds
	 * @throws
	 */
	private void bindECard(String accId, Long rechargeAmt, String cardIds) throws Exception{
		String[] cardArr = cardIds.split(",");
		for(String cardNo : cardArr) {
			AccECard accECard = new AccECard();
			accECard.setAccId(accId);
//			accECard.setAccNo(accNo);
			accECard.setCardMark(CardMarkConstant.ELEC_CARD);
			accECard.setCardNo(cardNo);
			accECard.setId(CommonUtils.getUUID());
			accECard.setFaceValue(rechargeAmt);
//			accECard.setExpiryDate(expiryDate);TODO 需要指定过期时间
			accECard.setIsDeleted(false);
			accECard.setCreateTime(DateUtil.dateTimeToString(new Date()));
			accECard.setCreator(accId);
			accECard.setRemark(null);
			accECard.setStatus(ECardStatus.NORMAL);
			accECard.setUpdater(accId);
			accECard.setUpdateTime(DateUtil.dateTimeToString(new Date()));
			this.accECardService.saveOrUpdate(accECard);
		}
	}
	/**
	 * @param status 
	 * 售卡订单返回对象
	 * @Title: createOrderReturn  
	 * @Description:  
	 * @param order
	 * @return
	 * @throws
	 */
	private JSONObject createOrderReturn(DTOSaleCardOrder order,SaleCardOrderDetail saleCardOrderDetail, int status) {
		JSONObject jo = new JSONObject();
		jo.put("account_id", order.getAccId());
		jo.put("card_no", order.getCardNo());
		jo.put("mrch_id", order.getMrchId());
		jo.put("mrch_name", order.getMrchName());
		jo.put("sale_count", order.getSaleCount());
		jo.put("denomination", order.getDenomination());
		jo.put("order_no", order.getOrderNo());
		if(status == 0) {
			jo.put("order_status", order.getOrderStatus());
		}else if(status == 1) {
			jo.put("order_status", "4");
		}else {
			jo.put("order_status", OrderStatus.PayFail.getStatus());//其他状态，认为是购卡失败
		}
		jo.put("amount", order.getRealPay());
		jo.put("order_detail", order.getOrderDetail());
		jo.put("pay_type", order.getPayment());
		jo.put("pay_status", order.getPayStatus());
		return jo;
	}
	
	private JSONObject createEntityListReturn(List<DTOEntityCardOrder> list) {
		JSONObject res = new JSONObject();
		JSONArray ja = new JSONArray();
		if(list != null && list.size() > 0) {
			for(DTOEntityCardOrder order : list) {
				JSONObject jo = new JSONObject();
				jo.put("account_id", order.getAccId());
				jo.put("order_no", order.getOrderNo());
				jo.put("pay_status", order.getPayStatus());
				jo.put("order_time", order.getCreateTime());
				jo.put("order_status", order.getOrderStatus());
				jo.put("entity_status", order.getEntityStatus());
				jo.put("amount", order.getRealPay());
				jo.put("order_detail", order.getOrderDetail());
				jo.put("pay_type", order.getPayment());
				ja.add(jo);
			}
		}
		res.put("entity_list", ja);
		return res;
	}
	
	private JSONObject createCommoditOrderListReturn(List<DTOCommoditOrder> list) {
		JSONObject res = new JSONObject();
		JSONArray ja = new JSONArray();
		if(list != null && list.size() > 0) {
			for(DTOCommoditOrder order : list) {
				JSONObject jo = new JSONObject();
				jo.put("account_id", order.getAccId());
				jo.put("order_no", order.getOrderNo());
				jo.put("pay_status", order.getPayStatus());
				jo.put("order_time", order.getCreateTime());
				jo.put("order_status", order.getOrderStatus());
				jo.put("state", order.getState());
				jo.put("amount", order.getRealPay());
				jo.put("order_detail", order.getOrderDetail());
				jo.put("pay_type", order.getPayment());
				jo.put("mrch_name", order.getMrchName());
				ja.add(jo);
			}
		}
		res.put("commodit_list", ja);
		return res;
	}
	
	private JSONObject createEntityReturn(DTOEntityCardOrder order) {
		JSONObject jo = new JSONObject();
		if(order != null) {
			jo.put("account_id", order.getAccId());
			Account acc = this.accountService.findById(order.getAccId());
			if(acc != null) {
				jo.put("phone_no", acc.getPhoneNo());
			}else {
				jo.put("phone_no", "");
			}
			jo.put("order_type", order.getOrderType());
			jo.put("order_type_desc", OrderType.getOrderTypeName(order.getOrderType()));
			jo.put("order_no", order.getOrderNo());
			jo.put("pay_status", order.getPayStatus());
			jo.put("order_time", order.getCreateTime());
			jo.put("order_status", order.getOrderStatus());
			jo.put("entity_status", order.getEntityStatus());
			jo.put("amount", order.getRealPay());
			jo.put("pay_type", order.getPayment());
			jo.put("order_detail", order.getOrderDetail());
			jo.put("address", order.getAddress());
			jo.put("mrch_name", order.getMrchName());
		}
		return jo;
	}
	
	private String getOrderDetail(JSONArray ja) {
		return ja.toJSONString();
	}
}
